package com.yi.wood;

import com.alibaba.fastjson.serializer.SerializerFeature;
import com.alibaba.fastjson.support.config.FastJsonConfig;
import com.alibaba.fastjson.support.spring.FastJsonHttpMessageConverter;
import com.yi.wood.web.socket.SystemWebSocket;
import com.yi.wood.web.util.UserCacheUtil;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.boot.autoconfigure.domain.EntityScan;
import org.springframework.boot.autoconfigure.http.HttpMessageConverters;
import org.springframework.context.ConfigurableApplicationContext;
import org.springframework.context.annotation.Bean;
import org.springframework.data.jpa.repository.config.EnableJpaRepositories;
import org.springframework.http.MediaType;
import org.springframework.http.converter.HttpMessageConverter;

import java.nio.charset.Charset;
import java.util.ArrayList;
import java.util.List;

/**
 * @author moyi
 * @since 1.0
 * 昨夜西风凋碧树
 */
@SpringBootApplication(scanBasePackages = "com.yi.wood")
@EnableJpaRepositories(basePackages = "com.yi.wood")
@EntityScan(basePackages = "com.yi.wood.entity")
public class WoodWebStarter {

    public static void main(String[] args) {
        ConfigurableApplicationContext context = SpringApplication.run(WoodWebStarter.class,args);
        UserCacheUtil userCacheUtil = (UserCacheUtil) context.getBean("userCacheUtil");
        SystemWebSocket.setUserCacheUtil(userCacheUtil);
    }

    /**
     * 配置FastJson
     * @return  HttpMessageConverters
     */
    @Bean
    public HttpMessageConverters fastJsonHttpMessageConverters() {
        // 1.定义一个converters转换消息的对象
        FastJsonHttpMessageConverter fastConverter = new FastJsonHttpMessageConverter();
        // 2.添加fastjson的配置信息，比如: 是否需要格式化返回的json数据
        FastJsonConfig fastJsonConfig = fastConverter.getFastJsonConfig();
        fastJsonConfig.setSerializerFeatures(SerializerFeature.PrettyFormat);
        fastJsonConfig.setCharset(Charset.forName("utf-8"));
        fastJsonConfig.setDateFormat("yyyy-MM-dd HH:mm:ss");

        // 解决乱码
        List<MediaType> fastMediaTypes = new ArrayList<>();
        fastMediaTypes.add(MediaType.APPLICATION_JSON_UTF8);
        fastConverter.setSupportedMediaTypes(fastMediaTypes);

        // 3.在converter中添加配置信息
        fastConverter.setFastJsonConfig(fastJsonConfig);
        // 4.将converter赋值给HttpMessageConverter
//        HttpMessageConverter<?> converter = fastConverter;
        // 5.返回HttpMessageConverters对象
        return new HttpMessageConverters(fastConverter);
    }
}
